<?php

// +----------------------------------------------------------------------
// |产品服务层
// +----------------------------------------------------------------------

namespace app\Api\system;

use think\facade\Validate;
use think\facade\Db;
use think\facade\Cache;
use app\common\Model\ConfigModel;
use app\common\library\ImageUploadOptimizer;

class GetProducrServicr
{  

   //dh.categorys.get$1.0 (获取类目列表接口)
  public static function category_get($accessToken)
    {
        $method='dh.categorys.get';
        $sysParams = [
          'method' => $method,
          'v' => '1.0',
          'access_token' => $accessToken,
          'timestamp' => round(microtime(true) * 1000)       
        ];
        $res=crul($sysParams);  
        $data=[]; 
        if($res['categoryPublishList']){
            foreach ($res['categoryPublishList'] as  $v) {
                $data[]=[
                    'pubnameCn'=>$v['pubNameCn'],//分类中文名称
                    'pubname'=>$v['pubName'],// 分类英文名称
                    'catepubid'=>$v['catePubId'],//发布类目id（物理父级类目id + 自身id 每段为3位）
                    'leaf'=>$v['leaf'],//是否叶子类目（1：是， 0：不是）
                    'remark'=>$v['remark'],//说明
                    'inlucdekeywords'=>$v['inlucdeKeywords'],//关键词
                    'valid'=>$v['valid'],//是否有效类目（1：是， 0：不是）
                    'stockwarnRatio'=>$v['stockWarnRatio'],//备货数量不足提醒， 比例(<1, 例如:0.8)
                    'stockPeriod'=>$v['stockPeriod'],//备货期
                    'createymd'=> date('Ymd'),//添加时间
                    'createtime'=>date('y-m-d H:i:s')//添加时间  
                ];
            }  
              if($data){
                Db::name('catego')->insertAll($data);
                return '数据插入成功';
              }else{
                return '数据插入失败'; 
              } 

        }else{
            return '无数据';
        }    
    }
  

    //dh.category.list$2.0 (获取类目列表接口)
    public static function category_list($accessToken){
      //查询所有一级类目
         $catego= Db::name('catego')->where(['leaf'=>'0','valid'=>'1','parecatepubId'=>'0'])->column('catepubid');
        $data=[];
        foreach ($catego as  $v) {
               $method='dh.category.list';
                $sysParams = [
                  'method' => $method,
                  'v' => '2.0',
                  'access_token' => $accessToken,
                  'timestamp' => round(microtime(true) * 1000),
                  'parentId'=>$v
                ];
                $res=crul($sysParams); 
            if($res['catePubList']){
                foreach ($res['catePubList'] as  $v) {
                    $data[]=[
                        'pubnameCn'=>$v['pubNameCn'],//分类中文名称
                        'pubname'=>$v['pubName'],// 分类英文名称
                        'catepubid'=>$v['catePubId'],//发布类目id（物理父级类目id + 自身id 每段为3位）
                        'leaf'=>$v['leaf'],//是否叶子类目（1：是， 0：不是）
                        'remark'=>$v['remark'],//说明
                        'parecatepubId'=>$v['pareCatePubId'],//关键词
                        'createymd'=> date('Ymd'),//添加时间
                        'createtime'=>date('y-m-d H:i:s')//添加时间  
                    ];
                }                

            }  
        }
        if($data){
          Db::name('catego')->insertAll($data);
          return '数据插入成功';
        }else{
          return '数据插入失败'; 
        } 
    }

    //dh.category.get$2.0 (获取类目详细信息接口)
    public static function category_get_datail($accessToken)
    {
        $catego= Db::name('catego')->where(['leaf'=>'1'])->column('catepubid');  
        $data=[];
        foreach ($catego as  $v) {
           $method='dh.category.get';
            $sysParams = [
              'method' => $method,
              'v' => '2.0',
              'access_token' => $accessToken,
              'timestamp' => round(microtime(true) * 1000),
              'catePubId'=>$v
            ];
            $res=crul($sysParams); 
            if($res['categoryPubAttrList']){
                foreach ($res['categoryPubAttrList'] as  $v) {
                    $data[]=[
                        'lineAttrnameCn'=>$v['lineAttrNameCn'],//分类中文名称
                        'lineAttrname'=>$v['lineAttrName'],// 分类英文名称
                        'catepubid'=>$v['catePubId'],//发布类目id
                        'required'=>$v['required'],//设置该属性设置是否为必填项；1：必填项， 0：非必填项;示例值：1
                        'type'=>$v['type'],//类目相关参数选择形式 ；1：多选框 2：下拉框 4：字符型输入框 5：数值型输入框;示例值：1
                        'isBrand'=>$v['isBrand'],//是否是品牌属性 1：是，0：不是
                        'saleAttr'=>$v['saleAttr'],//是否销售属性 1：是销售属性，0：非销售属性，通过该属性定义价格
                        'childAttrId'=>$v['childAttrId'],//子属性id
                        'catePubAttrId'=>$v['catePubAttrId'],//发布类目属性编号
                        'style'=>$v['style'],//类目选择样式 类目相关参数的选择样式 ；1：文本 2：图片 3：图文；
                        'attrId'=>$v['attrId'],//属性Id
                        'located'=>$v['isBrand'],//是否定位属性 1：定位属性，0：非定位属性，定位属性不可能是销售或购买属性;为平台定义好的属性值卖家不可更改
                        'values'=>json_encode($v['categoryPubAttrValList'],JSON_UNESCAPED_UNICODE),//属性                        
                    ];
                } 
             }  
        }
        if($data){
          Db::name('attribute')->insertAll($data);
          return '数据插入成功';
        }else{
          return '数据插入失败'; 
        } 
       
    }  



    


    // dh.item.list$2.0 (卖家获取产品列表接口)
    public  static function item_list($accessToken)
    {
        $method='dh.item.list';
        $sysParams = [
          'method' => $method,
          'v' => '2.0',
          'access_token' => $accessToken,
          'timestamp' => round(microtime(true) * 1000),
          'updateDate' => date('Y-m-d H:i:s'),
          'pageNum' => '1',
          'pageSize' => '20',
           'operateDateStart'=>date('Y-m-d H:i:s'),

        ];
        $res=crul($sysParams);
        return $res;
    }
    
    
    //dh.categorys.commissions$1.0 (获取佣金率列表)
    public static function  commissions($accessToken,$shop_id){
       $method='dh.categorys.commissions';
        $sysParams = [
          'method' => $method,
          'v' => '1.0',
          'access_token' => $accessToken,
          'timestamp' => round(microtime(true) * 1000),        
        ];   
         $data=[];    
        $res=crul($sysParams);
        Db::startTrans();
        try{
          if($res['list']){
              foreach ($res['list'] as  $v) {
                $cateId=$v['cateId'];
                $commissions=[$v['unitList'][0]['leftBound'].'-'.$v['unitList'][0]['rightBound']=>$v['unitList'][0]['commissionRate'],$v['unitList'][1]['leftBound'].'-'.$v['unitList'][1]['rightBound']=>$v['unitList'][1]['commissionRate'],$v['unitList'][2]['leftBound'].'-'.$v['unitList'][2]['rightBound']=>$v['unitList'][2]['commissionRate']];
                $commission=json_encode($commissions,JSON_UNESCAPED_UNICODE);
                Db::name('catego')->where('catepubid',$cateId)->update(['commission'=>$commission]);
              }             
          }
        }catch (\Exception $e) {
          // 回滚事务
          Db::rollback();
          // 记录错误或返回错误信息
           return '处理失败'.$e->getMessage();      
       }       
        return '处理成功';
    }

    //dh.item.group.list$2.0 (获取产品组列表接口)
     public static function group_list($accessToken){
        $method='dh.item.group.list';
        $sysParams = [
          'method' => $method,
          'v' => '2.0',
          'access_token' => $accessToken,
          'timestamp' => round(microtime(true) * 1000),
          'pageNo' => '1',
          'pageSize' => '30'         

        ];
        $res=crul($sysParams);
        return $res;
     }


     ############################上传图片############################
   
 //dh.item.group.list$2.0 (获取产品组列表接口)
    public static function  album_image_update($accessToken,$shop_id){
        $redis = Cache::store('redis')->handler();
        $shops=Db::name('shops')->where(['id'=>$shop_id])->field('name,iswatermark')->find();
        //查询那些图片是没有上传过的
        if( $redis->llen('res_img_list')==0){
          $result = Db::table('erp_products')
            ->alias('a')
            ->leftJoin('erp_hg_product_image b', 'a.id = b.product_id and  b.shop_id='.$shop_id )
            ->where('a.pid', 0)
            ->whereNull('b.imgarr')
            ->where('a.imgarr', '<>', '')         
            ->column('a.id');
            $redis->lpush('res_img_list', ...$result);
            
         }
         $product_id=$redis->rpop('res_img_list');
        if(empty($product_id)){
            return '没有需要上传的图片';
        }
 
          $img = Db::table('erp_products')->where('id', $product_id)->value('imgarr');  
          $imgarr=explode(',',$img);
          $method='dh.album.img.upload';//上传图片接口
          $img_url=$data=[];
         $imgarr = array_slice($imgarr, 0, 10);
          if($shops['iswatermark']==1){
            $optimizer = new ImageUploadOptimizer();
              $data = $optimizer->processImages($imgarr, $shops, $product_id, $shop_id, $method, $accessToken);
             
         }else{              
            foreach ($imgarr as $k => $v) {                 
                 $imageData = file_get_contents($v);
                 $base64=base64_encode($imageData);                 
                 $sysParams = [
                    'method' => $method,
                    'v' => '2.0',
                    'access_token' => $accessToken,
                    'timestamp' => round(microtime(true) * 1000),
                    'funType' => 'albu',
                    'imageBase64' => $base64,
                    'imageBannerName' => '',
                    'imageName' => $product_id.'-'.$shop_id.'.jpg'
                 ];
                 $res=post_crul($sysParams);       
                 if($res['productImg']){
                      $img_url['l_imgurl']=$res['productImg']['l_imgurl'];
                      $img_url['l_imgmd5']=$res['productImg']['l_imgmd5'];
                      $img_url['l_localfilename']=$res['productImg']['l_localfilename'];
                      $img_url['l_imgsize']=$res['productImg']['l_imgsize'];
                 }  
                 $data[]= $img_url;      
            } 
         }     
          if($data){
            if(Db::name('hg_product_image')->where(['product_id'=>$product_id,'shop_id'=>$shop_id])->find()){
                $insert_resrult= Db::name('hg_product_image')->where(['product_id'=>$product_id,'shop_id'=>$shop_id])->update(['imgarr'=>json_encode($data,JSON_UNESCAPED_UNICODE)]);
              }else{
                    $insert_data['imgarr']=json_encode($data,JSON_UNESCAPED_UNICODE);
                    $insert_data['shop_id']=$shop_id;
                    $insert_data['product_id']=$product_id;
                    $insert_resrult=Db::name('hg_product_image')->insert($insert_data);
              }
              if($insert_resrult){
                  return '数据插入成功';
              }else{
                  return '数据插入失败'; 
              }            
          }else{
            return '数据插入失败'; 
          }      
    }
     

     
        
 //dh.item.group.list$2.0 (获取产品组列表接口)
    public static function  album_image_dateil($accessToken,$shop_id){
        $redis = Cache::store('redis')->handler();
        $shops=Db::name('shops')->where(['id'=>$shop_id])->field('name,iswatermark')->find();

       //查询那些图片是没有上传过的
        if( $redis->llen('res_img_content')==0){
          $result = Db::table('erp_products')
            ->alias('a')
            ->leftJoin('erp_hg_product_image b', 'a.id = b.product_id and  b.shop_id='.$shop_id )
            ->where('a.pid', 0)
            ->whereNull('b.content')
            ->where('a.content', '<>', '')         
            ->column('a.id');
            $redis->lpush('res_img_content', ...$result);            
         }
         $product_id=$redis->rpop('res_img_content');
         if(empty($product_id)){
            return '没有需要上传的图片';
         }

         $img = Db::table('erp_products')->where('id', $product_id)->value('content');       
         //获取详情中得图片信息
          preg_match_all('/<img[^>]+src="([^"]+)"[^>]*>/i', $img, $matches);
          print_r($product_id);
          $imageUrls = $matches[1] ?? [];
          $method='dh.album.img.upload';//上传图片接口
          $img_url=$data=[];
         $imageUrls = array_slice($imageUrls, 2, 12);
          if($shops['iswatermark']==1){
              
             //等于0，则不需要添加水印，反则需要添加水印
              foreach ($imageUrls as $k => $v) {                 
                  $base6=addSlantedWatermarkToImageUrl($v,$shops['name']);
                  $imageData = file_get_contents('https://zixingche.net/'.$base6);
                  $base64=base64_encode($imageData);
                  $sysParams = [
                    'method' => $method,
                    'v' => '2.0',
                    'access_token' => $accessToken,
                    'timestamp' => round(microtime(true) * 1000),
                    'funType' => 'albu',
                    'imageBase64' => $base64,
                    'imageBannerName' => '',
                    'imageName' => $product_id.'-'.$shop_id.'.jpg'
                 ];
                 $res=post_crul($sysParams); 
                 unlink(root_path().'public'.$base6);//删除服务器的图片
                 if($res['productImg']){
                     $img_url['l_imgurl']=$res['productImg']['l_imgurl'];
                     $img_url['l_imgmd5']=$res['productImg']['l_imgmd5'];
                     $img_url['l_localfilename']=$res['productImg']['l_localfilename'];
                     $img_url['l_imgsize']=$res['productImg']['l_imgsize'];
                 }  
                 $data[]= $img_url;      
              } 
         }else{              
            foreach ($imageUrls as $k => $v) {                 
                 $imageData = file_get_contents($v);
                 $base64=base64_encode($imageData);                 
                 $sysParams = [
                    'method' => $method,
                    'v' => '2.0',
                    'access_token' => $accessToken,
                    'timestamp' => round(microtime(true) * 1000),
                    'funType' => 'albu',
                    'imageBase64' => $base64,
                    'imageBannerName' => '',
                    'imageName' => $product_id.'-'.$shop_id.'.jpg'
                 ];
                 $res=post_crul($sysParams);       
                 if($res['productImg']){
                      $img_url['l_imgurl']=$res['productImg']['l_imgurl'];
                      $img_url['l_imgmd5']=$res['productImg']['l_imgmd5'];
                      $img_url['l_localfilename']=$res['productImg']['l_localfilename'];
                      $img_url['l_imgsize']=$res['productImg']['l_imgsize'];
                 }  
                 $data[]= $img_url;      
            } 
         }     
          if($data){
            if(Db::name('hg_product_image')->where(['product_id'=>$product_id,'shop_id'=>$shop_id])->find()){
                $insert_resrult= Db::name('hg_product_image')->where(['product_id'=>$product_id,'shop_id'=>$shop_id])->update(['content'=>json_encode($data,JSON_UNESCAPED_UNICODE)]);
              }else{
                    $insert_data['content']=json_encode($data,JSON_UNESCAPED_UNICODE);
                    $insert_data['shop_id']=$shop_id;
                    $insert_data['product_id']=$product_id;
                    $insert_resrult=Db::name('hg_product_image')->insert($insert_data);
              }
              if($insert_resrult){
                  return '数据插入成功';
              }else{
                  return '数据插入失败'; 
              }            
          }else{
            return '数据插入失败'; 
          } 
      }
 
       //dh.item.add$2.0 (卖家发布产品信息接口)
    public static function  item_add($accessToken,$params){   

          $attrid=$params['attrid'];
          $logistice_id=$params['logistice_id'];
          $user_id=$params['user_id'];
          $product_id=$params['product_id'];
          $measureid='0000000000000000000000000000000'.$params['measures'];
          //产品关键字1
          $keyWord1 =$params['keyword1'];
          $keyWord2 =$params['keyword2'];
          $keyWord3 =$params['keyword3'];
          //卖点
          $shortDesc=$params['shortdesc'];
          $shortDesc1=$params['shortdesc1'];
          $shortDesc2=$params['shortdesc2'];
          $shortDesc3=$params['shortdesc3'];
          $shortDesc4=$params['shortdesc4'];
          $method='dh.item.add';//上传图片接口
         
          $catepubid=$params['catepubid'];
            $price=0;
          $name=$params['title'];//产品名称
          //产品折扣区间
           $intervalprice =Db::name('intervalprice')->where(['shop_id'=>$params['shop_id'],'product_id'=>$product_id])->field('intervalprice')->find();
          
           $itemWholesaleRange=[];
            if(empty($intervalprice) || empty($intervalprice['intervalprice'])){
                //说明没有设置过
                $itemWholesaleRange=[ 
                        ['discount'=>'0','startQty'=>'30'],
                        ['discount'=>'0.18','startQty'=>'150'],              
                        ['discount'=>'0.30','startQty'=>'550'],       
                        ['discount'=>'0.53','startQty'=>'1000'],                
                      ];
            }else{
                 $intervalprices=json_decode($intervalprice['intervalprice'],true);
                 $price=$intervalprices[0]['price'];
                 foreach($intervalprices as $k=>$v){
                     if(!isset($v['discount'])){
                         $itemWholesaleRange[$k]['discount']=0.0;
                     }else{
                         if($v['discount']>=1){
                             $itemWholesaleRange[$k]['discount']=(float) $v['discount']/100;
                         }else{
                              $itemWholesaleRange[$k]['discount']=(float) $v['discount']/100;
                         }
                         
                     }
                      $itemWholesaleRange[$k]['startQty']=(int)$v['num'];
                 }
                
            }
         
          $itemImgs=Db::name('hg_product_image')->where(['product_id'=>$product_id,'shop_id'=>$params['shop_id']])->field('imgarr,content')->find();
          //查询属性
          $attributeList=Db::name('attribute')->where(['catepubid'=>$catepubid])->column('catepubid,attrid,values,lineAttrname','attrid');
      
            $itemattrId=$itemAttr=$itemattrIds=$itemAttrs=[];
          //业务点击选择的属性

          if($params['attribute']){       
           
                 $itemAttr=$params['attribute'];
          }            

          //产品图片列表
          $itemImgList=[];
          if($itemImgs['imgarr']){
            foreach (array_slice(json_decode($itemImgs['imgarr'],true), 0, 9) as $k => $v) {
              if($k==0){
                $type=2;
              }elseif($k==1){
                $type=3;
              }else{
                $type=1;
              }
              $itemImgList[]=[
                'imgMd5' => $v['l_imgmd5'],
                'imgUrl' => $v['l_imgurl'],
                'type' => $type,                
              ];
            }          
          }
               
          //产品自定义数据
          //itemSpecSelfDefList
          $itemSpecSelfDefList=$itemSkuList=[];//自定义规格列表
        
          if($attrid){
             //产品属性
              foreach ($attrid as $k=> $v ){
                       if(isset($v['option2_en'])){
                          $option1_en=$v['option1_en'].$v['option2_en'];
                      }else{
                          $option1_en=$v['option1_en'];
                      }
                      $id=$v['attrid'];
                   
                  if($v['sizeSpecTyp']==3){
                      $dh_img=json_decode($v['dh_img'],true);
                      $itemSpecSelfDefList[]= ['attrValId'=>"$id",'attrValName'=>$option1_en,'picUrl'=>$dh_img['l_imgurl']]; 
                      $itemattrIds[]=['sizeSpecType'=>3,'attrId' =>  9999,'attrValId' =>(int)$id];
                         //产品属性
                     $shiptoCountryPriceList=['retailPrice'=>(float)$v['sell_price'],'regionCode'=>"NA"];
                      $inventoryLocationPriceList=[
                         'retailPrice'=>(float)$v['sell_price'],
                         'inventoryLocation'=>'CN',
                         'shiptoCountryPriceList'=>[$shiptoCountryPriceList]
                      ];
                      //有备货时产品sku与备货地址关联信息
                      $itemSkuInvenList=[
                         'inventoryLocation'=>'CN',
                         'skuCode'=>'sku-'.date('d').'-'.$id,//卖家自定义产品sku编码
                         'skuMD5'=>'',//skuMD5值
                         'skuInventoryQty'=>9999,//产品备货数量
                         'saleStatus'=>1//是否可销售
                      ];
                      $itemSkuList[]=[
                        'saleStatus'=>1,//是否可销售
                      'inventory'=>9000,
                      'retailPrice'=>(float)$v['sell_price'],//产品零售价
                      'itemSkuInvenList'=> [$itemSkuInvenList],//有备货时产品sku与备货地址关联信息
                      'itemSkuAttrvalList'=>[['sizeSpecType'=>3,'attrId' =>  9999,'attrValId' =>(int)$id]],//产品SKU属性值列表
                      'shiptoCountryPriceList'=>[$shiptoCountryPriceList],
                        'inventoryLocationPriceList'=>[$inventoryLocationPriceList],
                      ];
                    //   $itemAttr[]=[
                    //           "isbrand" => 0,
                    //         "saleAttr" =>1 ,
                    //         "buyAttr" =>1,
                    //         "itemAttrValList" => [[
                    //             "attrId" => (int)9999,
                    //             "attrName" => 'Color',
                    //             "attrValId" => (int)$id,
                    //             "brandId" => "",
                    //             "lineAttrvalName" => 'random',
                    //             "lineAttrvalNameCn" => $v['color'],
                    //             "picUrl" =>  $dh_img['l_imgurl']
                    //             ]]
                    //       ];
                      
                  }else{
                  
                         //产品属性
                     $shiptoCountryPriceList=['retailPrice'=>(float)$price,'regionCode'=>"NA"];
                      $inventoryLocationPriceList=[
                         'retailPrice'=>(float)$price,
                         'inventoryLocation'=>'CN',
                         'shiptoCountryPriceList'=>[$shiptoCountryPriceList]
                      ];
                      //有备货时产品sku与备货地址关联信息
                      $itemSkuInvenList=[
                         'inventoryLocation'=>'CN',
                         'skuCode'=>'sku-'.date('d').'-'.$id,//卖家自定义产品sku编码
                         'skuMD5'=>'',//skuMD5值
                         'skuInventoryQty'=>9999,//产品备货数量
                         'saleStatus'=>1//是否可销售
                      ];
                      $itemSkuList[]=[
                        'saleStatus'=>1,//是否可销售
                       'inventory'=>9000,
                       'retailPrice'=>(float)$price,//产品零售价
                       'itemSkuInvenList'=> [$itemSkuInvenList],//有备货时产品sku与备货地址关联信息
                       'itemSkuAttrvalList'=>[['sizeSpecType'=>0,'attrId' => $id ,'attrValId' =>$v['attrValId']]],//产品SKU属性值列表
                       'shiptoCountryPriceList'=>[$shiptoCountryPriceList],
                        'inventoryLocationPriceList'=>[$inventoryLocationPriceList],
                      ];
                  }
                  
              }
          }
        
 
          if($itemattrIds){
              $itemattrId=array_merge($itemattrId,$itemattrIds);
          }
            
          //产品折扣区间
          $itemWholesaleRangeList=$itemWholesaleRange;
          //产品销售属性设置
          $itemSaleSetting=[
            'leadingTime'=>7,//定制产品备货期
            'minWholesaleQty'=>1,//买家一次最大购买量
            'maxSaleQty'=>10000,//买家一次最大购买量
            'priceConfigType'=>2,//1分别设置价格，2 统一设置价格；若产品无规格，该字段设置为2(统一设置价格)；示例值：1；
          ];
     
          //产品包装信息
          $itemPackage=[
            'grossWeight'=>1.1,//产品包装后重量以KG为单位；
            'measureId'=>"$measureid",   //产品销售单位ID
            'height'=>50.1,//产品包装后高度以CM为单位；
            'width'=>50.1,//产品包装后宽度以CM为单位
            'packingQuantity'=>1,
            'length'=>50.1,//产品包装后长度以CM为单位；
          ];
      
          //产品属性
          $invenLocationList[]=[ 
              'sortVal'=>1,
                'leadingTime'=>7,//备货周期
                'inventoryLocation'=> 'CN',//产品备货地
                ];
         //产品备货信息
          $itemInventory=[
            'subtractStockType'=>2,//扣减库存类型，1-下单减库存，2-付款减库存
            'ifInTransit'=>1,//是否是备货途中 0-不是，1-是，不传按老的规则走
            'inventoryQty'=>9999,//产品备货数量
            'inventoryLocation'=>'CN',//产品备货地
            'invenLocationList'=>$invenLocationList          
            ];

          //产品属性列表
          $itemAttrList=$itemAttr;
          $htmlContent=[];
          $content=json_decode($itemImgs['content'],true);
          if($content){
              foreach ($content as $item){
                  $l_imgurl=$item['l_imgurl'];
                  $htmlContent[]="<img  src=http://image.dhgate.com/".$l_imgurl." /referrerpolicy=no-referrer><br/>";
              }
          }

           
          //产品基础信息
          $itemBase=[
            'htmlContent'=>'<p id="offer-template-0"><strong>Regarding Color</strong><p><p id="offer-template-0">
        The images provided are for reference only. Due to the limitations of photography techniques and the inevitable variations in display settings, the colors depicted in the pictures might not precisely replicate the actual colors of the product. There could be minor discrepancies, and the actual product"s colors should be considered as the standard.</p><p id="offer-template-0"><strong>
        Regarding Shipping</strong><p><p id="offer-template-0">
        Once your order is confirmed, we"ll make every effort to dispatch your purchased item promptly. It"s essential that you double - check the accuracy of your shipping address. Please note that shipping might be postponed during holidays. We sincerely hope you can understand these potential delays.</p><p id="offer-template-0"><strong>
        Regarding Size</strong></p><p id="offer-template-0">
        As the product"s dimensions are determined through manual measurement, there might be an approximate deviation of 2 - 3 centimeters. This slight difference is a normal result of the manual measuring process and should be expected.</p><p id="offer-template-0"><strong>
        
        Regarding Feedback</strong></p><p id="offer-template-0">
        Your satisfaction with our shopping experience and positive feedback are extremely significant to us. If you"re satisfied with our products and services, we"d greatly appreciate it if you could leave us a positive review. It would be a great source of pride for our team. If you have any queries regarding the product, don"t hesitate to get in touch with us. We"ll respond to your questions right away.</p><p id="offer-template-0"><strong>
        Customer Service</strong></p><p id="offer-template-0">
        Should you require any assistance, feel free to reach out to us through online chat (instant messaging) or email. Rest assured, we"ll respond promptly upon seeing your message. In case you"re not satisfied with our products or services, kindly get in touch with us before leaving negative feedback. We"re committed to providing you with a service that meets your expectations.</p><p'.implode(',',$htmlContent),//产品详情
            'itemName'=>mb_substr($name, 0, 139, 'UTF-8'),//产品名称
            'videoUrl'=>'',//产品视频地址
             'keyWords'=>$keyWord1,//产品关键字1
            'keyWord2'=>$keyWord2,//产品关键字2
            'keyWord3'=>$keyWord3,//产品关键字3
            'shortDesc'=>$shortDesc,//卖点
            'shortDesc1'=>$shortDesc1,//卖点
            'shortDesc2'=>$shortDesc2,//卖点
            'shortDesc4'=>'',//卖点
          ];
        
          //销售国家定价信息
          $itemShiptoSettingList[]=[
            'itemWholesaleRangeList'=>$itemWholesaleRangeList,//产品折扣区间
            'regionCode' => 'NA',//区域编码
            'shiptoCountryList' =>[
                  'US',
            ],//销售国家
          ];
          $shiptoCountryPriceList['shiptoCountryPriceList']=[
                    'retailPrice'=>0.0,
                    'regionCode'=>'NA',
                ];
      
        //   $itemAttrgroupDetailList[]=['itemAttrgroupDetailList'=>[
        //          'attrValId'=>0,
        //          'attrNameCn'=>'',
        //          'attrId'=>0,
        //          'lineAttrvalName'=>'',
        //          'attrName'=>'',
        //          'lineAttrvalNameCn'=>''
        //       ]];
    
        //   $itemAttrgroupDetailList[]=['itemAttrgroupDetailList'=>$itemAttrgroupDetailList];
          $redate=[];//信息返回
        //查询 售后模板
        $afterSaleTemplateId=Db::name('aftersale_template')->where('shop_id',$params['shop_id'])->field('aftersaletemplateid')->find();
        if(empty($afterSaleTemplateId)){
              $redate['status']=0;
              $redate['msg']='售后模板为空，请联系技术';
           return $redate;
          }
  
    $itemAttrgroupDetailList=[];
          $sysParams = [
              'method' => $method,
              'v' => '2.0',
              'access_token' => $accessToken,
              'timestamp' => round(microtime(true) * 1000),
              'afterSaleTemplateId' => $afterSaleTemplateId['aftersaletemplateid'],//产品售后模板id
              'shippingModelId' => "$logistice_id",//产品运费模板id
              'catePubId' => "$catepubid",//发布类目的id
              'itemAttrGroupList' =>  json_encode($itemAttrgroupDetailList,JSON_UNESCAPED_UNICODE),
              'itemImgList' => json_encode( $itemImgList,JSON_UNESCAPED_UNICODE),//产品图片列表
              'itemWholesaleRangeList' => json_encode( $itemWholesaleRangeList,JSON_UNESCAPED_UNICODE),//产品折扣区间
              'itemSaleSetting' => json_encode( $itemSaleSetting,JSON_UNESCAPED_UNICODE),//产品销售属性设置
              'itemPackage'=>json_encode($itemPackage,JSON_UNESCAPED_UNICODE),//产品包装信息            
              'itemBase'  => json_encode($itemBase,JSON_UNESCAPED_UNICODE),//产品基础信息
              'itemShiptoSettingList'  => json_encode($itemShiptoSettingList,JSON_UNESCAPED_UNICODE),//销售国家定价信息
            //  'itemCustomTypeInfo'  => json_encode($itemCustomTypeInfo,JSON_UNESCAPED_UNICODE),//商品定制信息
              'itemSpecSelfDefList'=>json_encode($itemSpecSelfDefList,JSON_UNESCAPED_UNICODE)  ,//自定义规格列表
              'itemSkuList'=>json_encode($itemSkuList,JSON_UNESCAPED_UNICODE) ,//产品SKU列表
              'itemInventory'=>json_encode($itemInventory,JSON_UNESCAPED_UNICODE),//产品备货信息
              'itemAttrList'=>json_encode($itemAttrList,JSON_UNESCAPED_UNICODE),  //产品属性列表            
          ];

        $res=post_crul($sysParams);
  
        if($res['status']['code']=='00000000'){
           $itemId= $res['itemId'];
          
           $itemCode= $res['itemCode'];
            $insert_data['product_id']=$product_id;
            $insert_data['user_id']=$user_id;
            $insert_data['shop_id']=$params['shop_id'];
            $insert_data['itemId']=$itemId;
            $insert_data['itemcode']=$itemCode;
            $insert_data['site']='US';
            $insert_data['createtime']=date('Y-m-d H:i:s');
            $data=Db::name('products_shelves')->insert($insert_data);
          
            if($data){
                $redate['status']=1;
                $redate['msg']='商品发布成功';
            }else{
               $redate['status']=0;
               $redate['msg']='商品保存失败';
            }
         }else{
              $redate['status']=0;
              if($res['status']['subErrors']){
                  foreach ($res['status']['subErrors'] as $k=>$v){
                     $msg[]=$k.':'.$v['message'];
                  }
              }
              $redate['msg']=implode(',', $msg);
         }
          return $redate;

      }


  //抓取1688的详情产品
   public static function item_detail_1688(){
     $redis = Cache::store('redis')->handler();
       
         
        if( $redis->llen('item_detail')==0){
             $products_list = Db::name('products')->where('detail_url', '<>', '')->whereNull('content')->where('pid', 0)->column('id');  
             $redis->lpush('item_detail', ...$products_list);
            
         }
         
         $product_id=$redis->rpop('item_detail');
        if(empty($product_id)){
            return '没有需要处理的详情';
        }
        $products = Db::name('products')->where(['id'=>$product_id])->field('detail_url')->find(); 

        $parts = explode('&offerId', $products['detail_url']);
        $parts = explode('url=', $parts[0]);
        $partss = $parts[1] ?? $parts[0];
        $result = curl_get_contents($partss);
       
        // $result = curl_get_contents(strpos($parent['detail_url'], 'http') === 0 ? $parent['detail_url'] : 'https:' . $parent['detail_url']);
        //解决中文乱码
        $result = mb_convert_encoding($result, 'utf-8', 'GB2312');
         
        //字符串截取
        if (preg_match('/\"content\":\"/', $result)){
            $result = get_sub_content($result, '"content":"', '"}');
        }else if (strpos($result, "var desc='") !== false){ 
            $result = get_sub_content($result, "var desc='", "';");        //去掉反斜杠
           
        }
         $pdetail = stripslashes($result);
        //调整样式
    
        $pdetail = str_replace(['left', 'div'], ['center', 'p'], $pdetail);
        $pattern = '/<img([^>]*)>/i';
        $replacement = '<img$1 referrerpolicy="no-referrer">';
        $pdetails = preg_replace($pattern, $replacement, $pdetail);
        if (!empty($pdetails)){               
            $res= Db::name('products')->where(['id'=>$product_id])->update(['content'=>$pdetails]);    
            if($res){
                return $product_id.'抓取成功';
            }else{
                return $product_id.'抓取失败';
            }  
        }else{
            return $product_id.'抓取失败';
        }

    }
}